package com.yuan.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuan.blog.constants.RedisKey;
import com.yuan.blog.dto.UserToken;
import com.yuan.blog.entity.SystemUser;
import com.yuan.blog.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @program: blog-system
 * @description:
 * @author: yuan_boss
 * @create: 2022-12-28 14:56
 **/
@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private Long defaultTimeOut = 30 * 60 * 1000L; // 默认超时时间是30分钟

    public UserToken createToken(SystemUser user) {
        UserToken token = new UserToken();
        Date createTime = new Date();
        token.setUsername(user.getUsername());//登录用户名
        token.setCreateTime(createTime);//登录时间
        token.setToken(UUIDUtils.getId());//令牌
        token.setUserId(user.getId());//登录用户id
        long timeout = createTime.getTime() + defaultTimeOut;
        token.setTimeout(new Date(timeout));

        // 以用户的token(令牌）作为key的唯一标识
        String key = String.format(RedisKey.USER_LOGIN_KEY, token.getToken());

        // 把用户的登录信息保存到redis中，过期时间是30m，
        redisTemplate.opsForValue().set(key, JSON.toJSONString(token), 30000000, TimeUnit.MINUTES);
        return token;
    }

    public UserToken getToken(String token) {
        String key = String.format(RedisKey.USER_LOGIN_KEY, token);
        String json = redisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, UserToken.class);
    }
}
